package com.ecar.mp.servlet;

import org.apache.commons.lang.StringUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

/**
 * 验证码图片生成
 * 
 */
public class ImgCodeServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (fc < 0)
			fc = 0;
		if (bc > 255)
			bc = 255;
		if (bc < 0)
			bc = 0;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String imgCode=request.getParameter("imgCode");
		if(StringUtils.isNotEmpty(imgCode)){
			String scode=(String)request.getSession().getAttribute("imgCode");
			PrintWriter out= response.getWriter();
			if(imgCode.equals(scode)){
				out.write("true");
			}else{
				out.write("false");
			}
			out.close();
		}else{
			response.setContentType("image/jpeg");
			int width = 60;
			int height = 20;
			Random r = new Random();
			BufferedImage imgbuf = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = imgbuf.createGraphics();
			g.setColor(getRandColor(200, 250));
			g.fillRect(0, 0, width, height);
			g.setColor(getRandColor(160, 200));
			for (int i = 0; i < 155; i++) {
				int x = r.nextInt(width);
				int y = r.nextInt(height);
				int xl = r.nextInt(12);
				int yl = r.nextInt(12);
				g.drawLine(x, y, x + xl, y + yl);
			}
			g.setColor(getRandColor(120, 240));
			for (int i = 0; i < 100; i++) {
				int x = r.nextInt(width);
				int y = r.nextInt(height);
				g.drawOval(x, y, 0, 0);
			}
			g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
			String scode = "";
			for (int i = 0; i < 4; i++) {
				String rand = String.valueOf(r.nextInt(10));
				scode += rand;
				g.setColor(new Color(20 + r.nextInt(110), 20 + r.nextInt(110), 20 + r.nextInt(110)));
				g.drawString(rand, 13 * i + 6, 16);
			}
			request.getSession().setAttribute("imgCode", scode);

			ImageIO.write(imgbuf, "JPEG", response.getOutputStream());

// Deprecated
//			ServletOutputStream out = response.getOutputStream();
//			// JPEGCodec.createJPEGEncoder(out);转码
//			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//			encoder.encode(imgbuf);
//			out.flush();
//			out.close();
		}
		
	}
}